package org.sample.commons.lang;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class DateUtils {

    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static long getMillis(LocalDateTime dateTime) {
        return dateTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli();
    }

    public static LocalDateTime getDateTime(Long millis) {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneOffset.systemDefault());
    }

    /**
     * 计算年龄
     */
    public static Integer getAge(LocalDate birthday) {
        LocalDate now = LocalDate.now();

        if (now.isBefore(birthday))
            return null;

        int yearNow = now.getYear();
        int monthNow = now.getMonthValue();
        int dayOfMonthNow = now.getDayOfMonth();

        int yearBirth = birthday.getYear();
        int monthBirth = birthday.getMonthValue();
        int dayOfMonthBirth = birthday.getDayOfMonth();

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                age--;
            }
        }
        return age;
    }
}